#include "Game.h"
#include "Console.h"

void Game::init(Handle* a_handle)
{
	m_running = true;
	m_core.init("Game",CL_BLACK,1280,720,true,a_handle);

	console::getInstance().init(&m_core);

	for (int i = 0; i < 20; i++)
	{
		char newChar[256];
		sprintf_s(newChar,"Hello World %d", i);
		console::getInstance().addString(newChar);
	}

	
	m_player.init(&m_core);
	ui.setPlayerStatus(m_player.getStatus());
	ui.init(&m_core);
	m_context.init(&m_core);
	m_clickable.m_core = &m_core;
	m_clickable.DOWN = 500;
	m_clickable.TOP = 400;
	m_clickable.RIGHT = 500;
	m_clickable.LEFT = 400;
	//addition by Jason Stewart
	m_maps.init(&m_core);
	m_context.addMenuItem("blah1");
	m_context.addMenuItem("blah2");
	m_context.addMenuItem("blah3");
	m_context.addMenuItem("blah4");
}

void Game::release()
{
	m_core.release();
	console::getInstance().release();
	m_maps.release();
	ui.release();
}

void Game::input()
{
	m_core.acquire();
	if(m_core.keyPress(DIK_GRAVE))
	{
		console::getInstance().toggleConsole();
	}
	if(console::getInstance().active())
	{
		if(m_core.keyPress(KEY_ESCAPE))
			console::getInstance().toggleConsole();
		else
			console::getInstance().input();
		return;
	}

	if(m_context.input())
		return;

	if(m_core.keyPress(KEY_ESCAPE))
		m_running = false;
}

void Game::update()
{
	TemplateVector<char*> m_files;
	m_core.update();
	//added by Jason Stewart
	//update maps
	m_maps.update();

	SAFE_RELEASE_LIST(m_files);
	if(console::getInstance().active())
		return;
	m_player.update();
	
	if(m_clickable.isClicked(BTN_RIGHT))
	{
		m_context.setStatus(true);
		int m_x;
		int m_y;
		m_core.mousePosition(&m_x,&m_y);
		m_context.setClicked(V2DF(m_x,m_y));
	}
	ui.update();
	
	m_context.update();
}

void Game::draw()
{
	m_core.drawBegin();
	ui.draw();
	m_maps.draw();
	m_player.draw();
	//added by jason stewart
	//draw maps
	m_maps.draw();
	m_context.draw();
	int color = 0xff00ff00;
	if(m_context.status())
		color = 0xfff00000;
	m_core.drawLine(V2DF(m_clickable.LEFT,m_clickable.TOP),V2DF(m_clickable.RIGHT,m_clickable.TOP),color);
	m_core.drawLine(V2DF(m_clickable.RIGHT,m_clickable.TOP),V2DF(m_clickable.RIGHT,m_clickable.DOWN),color);
	m_core.drawLine(V2DF(m_clickable.RIGHT,m_clickable.DOWN),V2DF(m_clickable.LEFT,m_clickable.DOWN),color);
	m_core.drawLine(V2DF(m_clickable.LEFT,m_clickable.TOP),V2DF(m_clickable.LEFT,m_clickable.DOWN),color);

	console::getInstance().draw();
	m_core.drawEnd();
}

void Game::preLoop()
{
}

void Game::postLoop()
{
}

bool Game::running(int& a_error)
{
	if(!m_running || m_core.exit())
	{
		a_error = m_core.exitMessage();
		return false;
	}

	return true;
}